package cn.ruituo.adv7.bank;

import java.util.Random;

public class MoneyTaker extends Thread {
    private Account ac;

    public MoneyTaker(String n, Account ac) {
        super(n);
        this.ac = ac;
    }
    @Override
    public void run() {
        Random r = new Random();
        while (true) {
            int m = r.nextInt(400);
            System.out.printf(super.getName()+"打算取钱%d元，当前账户的余额是%d元\n",m,ac.getMoney());
            synchronized (ac){
                boolean ok= ac.takeAway(m);
                System.out.println(super.getName()+"取钱："+m+"元,结果是："+ok+".当前余额是"+ac.getMoney());
                if(ok==false) {
                    try {
                        System.out.println(super.getName()+"取钱："+m+"元,结果是："+ok+",等着");
                        ac.wait();//会释放锁
                        System.out.println(super.getName()+"被喊醒，接着取钱");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

    }
//    @Override
//    public void run() {
//        Random r = new Random();
//        while (ac.getMoney() >0) {
//            int m = r.nextInt(100);
//            System.out.printf(super.getName()+"打算取钱%d元，当前账户的余额是%d元\n",m,ac.getMoney());
//            synchronized (ac){
//                boolean ok= ac.takeAway(m);
//                System.out.println(super.getName()+"取钱："+m+"元,结果是："+ok+".当前余额是"+ac.getMoney());
//            }
//        }
//        System.out.println("账户钱已经没有了，当前余额是"+ac.getMoney()+"元");
//    }
}
